
package org.apache.solr.highlight;

import java.text.BreakIterator;
import java.util.Locale;
import org.apache.lucene.search.vectorhighlight.BoundaryScanner;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.params.HighlightParams;
import org.apache.solr.common.params.SolrParams;

public class BreakIteratorBoundaryScanner extends SolrBoundaryScanner {

    @Override
    protected BoundaryScanner get(String fieldName, SolrParams params) {
        // construct Locale
        String language = params.getFieldParam(fieldName, HighlightParams.BS_LANGUAGE);
        String country = params.getFieldParam(fieldName, HighlightParams.BS_COUNTRY);
        if(country != null && language == null) {
            throw new SolrException(ErrorCode.BAD_REQUEST, HighlightParams.BS_LANGUAGE + " parameter cannot be null when you specify " + HighlightParams.BS_COUNTRY);
        }
        Locale locale;
        if(language != null) {
            locale = country == null ? new Locale(language) : new Locale(language, country);
        }
        else {
            locale = Locale.ROOT;
        }

        // construct BreakIterator
        String type = params.getFieldParam(fieldName, HighlightParams.BS_TYPE, "WORD").toLowerCase(Locale.ROOT);
        BreakIterator bi = null;
        switch(type) {
            case "character":
                bi = BreakIterator.getCharacterInstance(locale);
                break;
            case "word":
                bi = BreakIterator.getWordInstance(locale);
                break;
            case "line":
                bi = BreakIterator.getLineInstance(locale);
                break;
            case "sentence":
                bi = BreakIterator.getSentenceInstance(locale);
                break;
            default:
                throw new SolrException(ErrorCode.BAD_REQUEST, type + " is invalid for parameter " + HighlightParams.BS_TYPE);
        }

        return new org.apache.lucene.search.vectorhighlight.BreakIteratorBoundaryScanner(bi);
    }

    // SolrInfoMBeans methods
    @Override
    public String getDescription() {
        return "BreakIteratorBoundaryScanner";
    }

    @Override
    public String getSource() {
        return "$URL: https://svn.apache.org/repos/asf/lucene/dev/branches/lucene_solr_4_0/solr/core/src/java/org/apache/solr/highlight/BreakIteratorBoundaryScanner.java $";
    }
}
